package com.exampletest.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/user/login",
                        "/user/register",
                        "/enterprise/login",
                        "/enterprise/register",
                        "/admin/dashboard", // 确保管理员路径不被拦截
                        "/css/**",
                        "/js/**",
                        "/images/**",
                        "/"
                );
    }
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, Date.class, source -> {
            if (source == null || source.isEmpty()) {
                return null;
            }
            try {
                // 处理 datetime-local 格式: yyyy-MM-ddTHH:mm
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                return sdf.parse(source);
            } catch (ParseException e) {
                throw new IllegalArgumentException("日期格式错误，应为 yyyy-MM-ddTHH:mm", e);
            }
        });
    }
    @Value("${app.upload.path}")
    private String uploadPath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        registry.addResourceHandler("/uploads/images/**")
                .addResourceLocations("file:" + uploadPath);
    }
}